package com.ccteam.fluidmusic.ui.home

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.ConcatAdapter
import com.ccteam.fluidmusic.*
import com.ccteam.fluidmusic.databinding.*
import com.ccteam.fluidmusic.utils.TransitionUtils
import com.ccteam.fluidmusic.view.adapters.*
import com.ccteam.fluidmusic.view.adapters.onlinehome.OnlineMusicHomeFunctionCallback
import com.ccteam.fluidmusic.view.adapters.onlinehome.OnlineMusicHomeRVAdapter
import com.ccteam.fluidmusic.view.adapters.onlinehome.OnlineMusicHomeSmallItemCallback
import com.ccteam.fluidmusic.view.adapters.toolbar.ToolbarTitleAdapter
import com.ccteam.fluidmusic.view.base.LightBounceEdgeEffectFactory
import com.ccteam.fluidmusic.view.bean.*
import com.ccteam.fluidmusic.widget.AnimToolbarScrollListener
import com.ccteam.fluidmusic.ui.MainActivityViewModel
import com.ccteam.model.banner.BANNER_TYPE_ALBUM
import com.ccteam.shared.result.home.OnlineMusicBanner
import com.ccteam.shared.result.home.OnlineMusicHomeInnerSmallItem
import com.ccteam.shared.result.home.OnlineMusicHomeSmallItem.Companion.SMALL_ITEM_ALBUM
import com.ccteam.shared.result.home.OnlineMusicHomeSmallItem.Companion.SMALL_ITEM_MUSIC
import com.ccteam.shared.result.home.OnlineMusicHomeSmallItem.Companion.SMALL_ITEM_PLAYLIST
import com.ccteam.shared.result.title.ToolbarTitleItem
import com.orhanobut.logger.Logger
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject

/**
 * @author Xiaoc
 * @since 2021/3/18
 *
 * 在线音乐首页Fragment
 */
@AndroidEntryPoint
class OnlineMusicFragment : Fragment() {

    private var _binding: FragmentOnlineMusicBinding? = null
    private val binding get() = _binding!!

    @Inject lateinit var lightBounceEdgeEffectFactory: LightBounceEdgeEffectFactory

    private val onlineMusicHomeViewModel: OnlineMusicHomeViewModel by viewModels()
    private val mainActivityViewModel by activityViewModels<MainActivityViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        exitTransition = TransitionUtils.exitScale
        reenterTransition = TransitionUtils.enterScale
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View {
        _binding = FragmentOnlineMusicBinding.inflate(inflater,container,false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        val titleAdapter = ToolbarTitleAdapter()
        val bannerAdapter = OnlineMusicHomeRVAdapter(bannerCallback,
            onlineMusicHomeSmallItemClickedCallback,onlineMusicHomeClickCallback)
        val newAlbumAdapter = OnlineMusicHomeRVAdapter(bannerCallback,
            onlineMusicHomeSmallItemClickedCallback,onlineMusicHomeClickCallback)
        val newMusicAdapter = OnlineMusicHomeRVAdapter(bannerCallback,
            onlineMusicHomeSmallItemClickedCallback,onlineMusicHomeClickCallback)
        val hotPlaylistSheetAdapter = OnlineMusicHomeRVAdapter(bannerCallback,
            onlineMusicHomeSmallItemClickedCallback,onlineMusicHomeClickCallback)
        val hotMusicAdapter = OnlineMusicHomeRVAdapter(bannerCallback,
            onlineMusicHomeSmallItemClickedCallback,onlineMusicHomeClickCallback)

        lightBounceEdgeEffectFactory.applyBounceView(binding.rvOnlineMusicHome,this)
        binding.rvOnlineMusicHome.edgeEffectFactory = lightBounceEdgeEffectFactory

        binding.rvOnlineMusicHome.addOnScrollListener(
            AnimToolbarScrollListener(binding.toolbarTitle)
        )

        titleAdapter.submitList(mutableListOf(ToolbarTitleItem(getString(R.string.onlineMusic_name))))

        binding.toolbarOnlineMusicHome.setOnMenuItemClickListener { item ->
            return@setOnMenuItemClickListener when(item.itemId){
                R.id.toolbar_onlineMusic_search ->{
                    findNavController().navigate(OnlineMusicFragmentDirections.actionOnlineMusicFragmentToHomeSearchFragment())
                    true
                }
                else -> false
            }
        }

        val concatAdapter = ConcatAdapter(titleAdapter,bannerAdapter,newAlbumAdapter,newMusicAdapter,
            hotPlaylistSheetAdapter,hotMusicAdapter)
        binding.rvOnlineMusicHome.adapter = concatAdapter

        onlineMusicHomeViewModel.loadMessage.observe(viewLifecycleOwner, {
            binding.rvOnlineMusicHome.isVisible = it !is LoadMessage.Loading
            binding.statusView.changeToLoadingStatus(it is LoadMessage.Loading)
            binding.statusView.changeToErrorStatus(it)
            binding.refreshView.isRefreshing = it is LoadMessage.Loading
        })

        onlineMusicHomeViewModel.newAlbumRecommends.observe(viewLifecycleOwner, {
            newAlbumAdapter.submitList(it)
        })

        onlineMusicHomeViewModel.newMusicRecommends.observe(viewLifecycleOwner, {
            newMusicAdapter.submitList(it)
        })

        onlineMusicHomeViewModel.bannerItems.observe(viewLifecycleOwner, {
            bannerAdapter.submitList(it)
        })

        onlineMusicHomeViewModel.hotPlaylistSheetRecommends.observe(viewLifecycleOwner, {
            hotPlaylistSheetAdapter.submitList(it)
        })

        onlineMusicHomeViewModel.hotMusicRecommends.observe(viewLifecycleOwner, {
            hotMusicAdapter.submitList(it)
        })

        binding.statusView.setRetryClickListener {
            onlineMusicHomeViewModel.refreshOnlineHomeData()
        }

        binding.refreshView.setOnRefreshListener {
            onlineMusicHomeViewModel.refreshOnlineHomeData()
        }

    }


    private val onlineMusicHomeClickCallback = object: OnlineMusicHomeFunctionCallback {

        /**
         * 歌手类型按钮点击
         */
        override fun artistListClicked() {
            findNavController().navigate(OnlineMusicFragmentDirections.actionOnlineMusicFragmentToArtistListFragment())
        }
        /**
         * 歌单类型按钮点击
         */
        override fun playlistSheetClicked() {
            findNavController().navigate(NavPlaylistSheetListDirections
                .actionGlobalPlaylistSheetListFragment(null))
        }
        /**
         * 专辑类型按钮点击
         */
        override fun albumListClicked() {
            findNavController().navigate(OnlineMusicFragmentDirections.actionOnlineMusicFragmentToAlbumListFragment())
        }

    }

    private val onlineMusicHomeSmallItemClickedCallback = object: OnlineMusicHomeSmallItemCallback {

        /**
         * 横向RV中的Item点击事件
         */
        override fun smallItemClicked(type:Int,item: OnlineMusicHomeInnerSmallItem) {
            // 如果是专辑类，进行跳转到专辑详情
            if(type == SMALL_ITEM_ALBUM){
                findNavController().navigate(
                    NavAlbumDirections.actionGlobalAlbumDetailFragment(
                        item.itemId
                    ))
            } else if(type == SMALL_ITEM_MUSIC){
                // 如果是歌曲类，进行播放
                mainActivityViewModel.playMediaId(item.itemId,item.parentId,false,true)
            } else if(type == SMALL_ITEM_PLAYLIST){
                // 如果是歌单类，直接跳转歌单详情
                findNavController().navigate(
                    NavPlaylistSheetDirections.actionGlobalPlaylistSheetDetailFragment(
                        item.itemId
                    ))
            }
        }

        /**
         * 横向RV中的Item的更多按钮点击事件
         */
        override fun smallMoreClicked(type: Int) {
            if(type == SMALL_ITEM_ALBUM){
                findNavController().navigate(OnlineMusicFragmentDirections.actionOnlineMusicFragmentToNewAlbumFragment())
            } else if(type == SMALL_ITEM_MUSIC){
                findNavController().navigate(OnlineMusicFragmentDirections.actionOnlineMusicFragmentToNewMusicFragment())
            }
        }

    }

    private val bannerCallback = object: BannerCallback{
        override fun bannerItemClicked(item: OnlineMusicBanner) {
            if(item.type == BANNER_TYPE_ALBUM){
                findNavController().navigate(NavAlbumDirections.actionGlobalAlbumDetailFragment(
                    item.id
                ))
            } else {
                findNavController().navigate(NavArtistDirections.actionGlobalArtistDetailFragment(
                    item.id
                ))
            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        // 清除所有滑动监听
        binding.rvOnlineMusicHome.clearOnScrollListeners()
        _binding = null
    }

}